package office.service.person.impl;

import office.bo.hr.impl.CheckFolw;
import office.bo.person.LeaveRequest;
import office.domainset.BizDomainProviderSetImpl;
import office.service.finance.impl.CheckFolwServiceImpl;
import office.service.person.ILeaveService;
import platform.common.exception.BusinessException;
import platform.util.Util;

public class LeaveServiceImpl extends CheckFolwServiceImpl implements ILeaveService{

	@Override
	public CheckFolw getCheckFolwById(String id) throws BusinessException {
		LeaveRequest leave = null;
		try {
			BizDomainProviderSetImpl domainProviderSetImpl = (BizDomainProviderSetImpl) domainProviderSet;
			leave = (LeaveRequest)domainProviderSetImpl.getDao().findByIdAndDomain(domainProviderSetImpl.getLeaveRequestDP(), id);
		} catch (Exception e) {
			log.error("", e);
			throw this.handleBusinessServiceException("获取审批对象信息失败!", e);
		}
		return leave;
	}
	
	/**
	 * 
	 * @param check 审批是否为通过
	 * @param id
	 * @throws BusinessException
	 */
	public void checkData(boolean check,String id,String proKey)throws BusinessException{
		try {
			BizDomainProviderSetImpl domainProviderSetImpl = (BizDomainProviderSetImpl) domainProviderSet;
			CheckFolw checkFolw = this.getCheckFolwById(id);
			if(check){
				String nextRole = getNextCheckRole(checkFolw.getEntryRole(),checkFolw.getCheckRole(),proKey,checkFolw);
				if(nextRole.equals("end")){
					checkFolw.setState("100");
					checkFolw.setCheckRole("cwcn");
				}else{
					checkFolw.setCheckRole(nextRole);
				}
			}else{
				checkFolw.setCheckRole("");//重新提交审批,CheckRole重新赋值
				checkFolw.setState("-1");//审批驳回
			}
			checkFolw.store(domainProviderSet);//保存对象
		} catch (Exception e) {
			log.error("", e);
			throw this.handleBusinessServiceException("设置审批状态信息对象失败!", e);
		}
	}
	/**
	 * 
	 * @param key 配置文件key
	 * @param preRole 现在所处审批角色
	 * @return
	 * @throws BusinessException
	 */
	public String getNextCheckRole(String entryRole,String preRole,String proKey,CheckFolw checkFolw)throws BusinessException{
		String roles = Util.parsePropertiesReturnStr("office", proKey+"-"+entryRole);
		String role[] = roles.split(",");
		if(null==preRole || ("").equals(preRole)){
			if(role.length<2){
				throw new BusinessException("未找到下级审批节点,审批流程配配置错误");
			}
			return role[1];
		}
		//若是销售人员且请假时间大于等于3天需要xsjl审批
		if(entryRole.equals("xsry") || entryRole.equals("scry")){
			LeaveRequest leave = (LeaveRequest)checkFolw;
			//请假时间小于3天不需要xsjl审批(trip-xsry配置的是到最长的审批点)
			if(leave.getSumDay()<3 && (leave.getCheckRole().equals("qyjl") || leave.getCheckRole().equals("cjzr"))){
				return "end";
			}
		}
		if(roles.indexOf(",")>-1){
			if(roles.endsWith(","+preRole)){
				return "end";
			}else if(roles.endsWith(preRole)){
				return "end";
			}
		}
		
		for(int i=0; i<role.length;i++){
			if(role[i].equals(preRole)){
				return role[i+1];
			}
		}
		return "";
	}

}
